<template>
  <div>
<!--    <el-button type="primary" @click="dialogVisible = true">新增</el-button>-->
  </div>
  <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="id" label="服务类型id" width="130" />
    <el-table-column prop="code" label="服务类型编码" width="130" />
    <el-table-column prop="name" label="服务类型名称" width="130" />
    <el-table-column prop="serveTypeIcon" label="服务类型图标" width="130" v-slot="scope">
      <img :src="scope.row.img" alt="" style="width: 50px; height: 50px" />
    </el-table-column>
    <el-table-column prop="img" label="服务类型图片" width="130" v-slot="scope">
      <img :src="scope.row.img" alt="" style="width: 50px; height: 50px" />
    </el-table-column>
    <el-table-column prop="sortNum" label="排序字段" width="130" />
    <el-table-column prop="activeStatus" label="是否启用" v-slot="scope" width="130">
      <template v-if="scope.row.activeStatus == 1"> 禁用 </template>
      <template v-if="scope.row.activeStatus == 2"> 启用 </template>
    </el-table-column>
    <el-table-column prop="createTime" label="创建时间" width="180" />

    <el-table-column label="操作" width="200">
      <template #default="scope">
        <el-button type="danger" plain @click="dele(scope.row)">删除</el-button>
          <router-link :to="{path:'/item/index',query:{typeId:scope.row.id} }">查看服务类型</router-link>
        <el-button @click="qiyong(scope.row)" type="text" size="small" class="action-button" v-if="scope.row.activeStatus == 1">启用</el-button>
        <el-button @click="jinyong(scope.row)" type="text" size="small" class="action-button" v-if="scope.row.activeStatus == 2">禁用</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!--  //弹框-->
  <el-dialog v-model="dialogVisible" title="新增服务类型" width="500" :before-close="handleClose">
    <template #footer>
      <div align="left">
        <form @submit.prevent="onSubmit">
          <div>
            <label for="name">服务类型：</label>
            <input id="name" v-model="listtype" placeholder="请输入类型名称" />
            <span v-if="!listtype.name && listtype.submitted" class="error">服务类型不能为空</span>
          </div>
          <div>
            <label for="code">排序：</label>
            <input id="code" v-model="listtype" type="number" placeholder="请输入数字" />
            <span v-if="!listtype.code && listtype.submitted" class="error">排序不能为空</span>
          </div>
          <div>
            <!--      上传图片-->
            <el-form-item label="上传图标:" prop="listtype.qrCode">
              <el-upload
                :on-change="handleChange"
                class="avatar-uploader"
                action="/ruoyi-minio/minio/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>

            <el-form-item label="上传图片:" prop="listtype.qrCode">
              <el-upload
                :on-change="handleChange"
                class="avatar-uploader"
                action="http://localhost:9999/minio/minio/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submit()">提交</el-button>
            </el-form-item>
          </div>
        </form>
      </div>
    </template>
  </el-dialog>



  <el-pagination
    v-model:current-page="listtype.pageNum"
    v-model:page-size="listtype.pageSize"
    :page-sizes="[5, 10, 15, 20]"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />
</template>

<script setup>
  import { ref } from 'vue';
  import { addtype, gettype, deletype, starttype } from '@/api/type/type';
  import { ElMessage } from 'element-plus';
  import {useRoute} from "vue-router";
  const route=useRoute();
  const id=route.query.typeId
  const listtype = ref({
    typeId:id,
    id: '',
    name: '',
    sortNum: '',
    serveTypeIcon: '',
    img: '',
    submitted: '',
    pageNum: 1,
    pageSize: 5
  });


  //查询服务
  const tableData = ref([]);
  const total=ref(0)
  function findall() {
    gettype(listtype.value).then((res) => {
      tableData.value = res.data.data.data;
      total.value=res.data.data.total;
      console.log(res.data.data);
    });
  }
  findall();

  const handleSizeChange = (val) => {
    listtype.value.pageSize=val
    findall()
  }
  const handleCurrentChange = (val) => {
    listtype.value.pageNume=val
    findall()
  }
  //新增
  const dialogVisible = ref(false);


  //上传图片
  //   / 表单数据
  // const name = ref('');
  // const code = ref('');
  // const submitted = ref(false);

  // 服务类型图标相关
  const serviceTypeIcon = ref(null);
  const serviceTypeIconError = ref('');
  const handleServiceTypeIconUpload = () => {
    const file = serviceTypeIcon.value.files[0];
    const maxSize = 500 * 1024; // 500K
    const allowedTypes = ['image/jpeg', 'image/png'];
    if (file) {
      if (file.size > maxSize) {
        serviceTypeIconError.value = '文件大小超过500K限制';
      } else if (!allowedTypes.includes(file.type)) {
        serviceTypeIconError.value = '请上传jpg或png文件';
      } else {
        serviceTypeIconError.value = '';
      }
    }
  };

  // 服务类型图片相关
  const serviceTypePicture = ref(null);
  const serviceTypePictureError = ref('');
  const handleServiceTypePictureUpload = () => {
    const file = serviceTypePicture.value.files[0];
    const maxSize = 10 * 1024 * 1024; // 5M
    const allowedTypes = ['image/jpeg', 'image/png'];
    if (file) {
      if (file.size > maxSize) {
        serviceTypePictureError.value = '文件大小超过10M限制';
      } else if (!allowedTypes.includes(file.type)) {
        serviceTypePictureError.value = '请上传jpg或png文件';
      } else {
        serviceTypePictureError.value = '';
      }
    }
  };

  const onSubmit = () => {
    // 简单验证，如果所有必填项都有值，则模拟提交
    if (name.value && code.value && !serviceTypeIconError.value && !serviceTypePictureError.value) {
      console.log('提交表单数据：', {
        serviceType: name.value,
        sortOrder: code.value,
        serviceTypeIcon: serviceTypeIcon.value.files[0],
        serviceTypePicture: serviceTypePicture.value.files[0],
      });
      // 这里可以添加实际的提交逻辑，如发送API请求等
      addtype(listtype.value).then((res) => {
        ElMessage.success('添加成功');
        findall();
      });
    }
  };

  //删除
  const dele = (row) => {
    deletype(row.id).then((res) => {
      if (res.data.code == 200) {
        ElMessage.success('删除成功');
        findall();
      } else {
        ElMessage.error('删除失败');
      }
    });
  };

  //禁用
  const jinyong = (row) => {
    starttype(row.id).then((res) => {
      if (res.data.code == 200) {
        ElMessage.success('禁用成功');
        findall();
      } else {
        ElMessage.error('禁用失败');
      }
    });
  };

  //启用
  const qiyong = (row) => {
    starttype(row.id).then((res) => {
      if (res.data.code == 200) {
        ElMessage.success('启动成功');
        findall();
      } else {
        ElMessage.error('启动失败');
      }
    });
  };


  // 上传图片

  const imageUrl = ref('');

  const handleAvatarSuccess = (response, uploadFile) => {
    imageUrl.value = URL.createObjectURL(uploadFile.raw);
    console.log(uploadFile.raw);
    console.log(response);
    listtype.value.qrCode = response;
  };

  const beforeAvatarUpload = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
      ElMessage.error('Avatar picture must be JPG format!');
      return false;
    } else if (rawFile.size / 1024 / 1024 > 2) {
      ElMessage.error('Avatar picture size can not exceed 2MB!');
      return false;
    }
    return true;
  };
</script>
